package com.liu.spike.runner;

import com.liu.spike.entity.Product;
import com.liu.spike.mapper.ProductMapper;
import com.liu.spike.service.KafkaProducerServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @className: com.liu.spike.listener.AppStartListener
 * @description: TODO
 * @author: liu
 * @create: 2022-05-01 23:49
 */

@Slf4j
@Component
public class ProductCacheRunner implements CommandLineRunner {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    KafkaProducerServer kafkaProducerServer;

    @Override
    public void run(String... args) {
        log.info("log for AppStartListener:{}","start");
        List<Product> all = productMapper.getAll();
//        https://cloud.tencent.com/developer/article/1783938
        redisTemplate.executePipelined((RedisCallback<?>) redisConnection -> {
            RedisSerializer keySerializer = redisTemplate.getKeySerializer();
            RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
            all.forEach(item->
                    {
                        redisConnection.set(keySerializer.serialize(getProductKey(item)),valueSerializer.serialize(item.getStock()));
                        redisConnection.set(keySerializer.serialize(getProductKeyState(item)),valueSerializer.serialize("have"));
                    }
            );
            return null;
        });
    }

    private String getProductKey(Product product){
        return "product"+"-"+product.getId();
    }

    private String getProductKeyState(Product product){
        return "product"+"-"+"state"+"-"+product.getId();
    }

}
